import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-17
 * Time: 08:27
 */
public class EchoSever {
    private final DatagramSocket socket;
    //传入端口号
    public EchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        //服务器死循环就行了，想要关闭服务器直接杀进程
        while (true) {
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            //receive从网卡读取到UDP数据报，载荷部分放到byte数组里
            //UDP报头存放在requestPacket其他属性里
            //还能通过requestPacket知道源IP/端口
            //receive具有阻塞功能
            socket.receive(requestPacket);
            //将接收到的字节数组转换为字符串
            //requestPacket.getLength()得到的长度是有效长度，不一定是4096
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求计算相应(回显服务器啥都不用做)
            String response = process(request);
            //3.返回响应到客户端
            //response.getBytes()得到String内部的字节数组
            //当String里面全都是英文字符的时候，response.length()是可以的
            //requestPacket.getSocketAddress()找到对应客户端的IP和端口号
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            //IP,端口号,请求,响应
            System.out.printf("[%s:%d] request:%s,response:%s\n",requestPacket.getAddress().toString(),
                    responsePacket.getPort(),request,response);
        }
    }
    //根据请求计算相应
    public String process(String request){
        return request;
    }
    //
    public static void main(String[] args) throws IOException {
        EchoSever sever = new EchoSever(9090);
        sever.start();
    }
}
